package mobile.TheOldRepublic;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.io.IOUtils;

import com.explodingzombie.util.GeneralUtils;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import mobile.TheOldRepublic.util.Downloader;
import mobile.TheOldRepublic.util.Utils;

public class ImageDownloader extends Downloader {
	
	private static String FILE_ROOT = "_image.tmp";
	private static final String IMAGE_DIR = "images";
		
	private ImageDownloader(){
		
	}

	public static Downloader getInstance(){
		if(activeThread == null){
			activeThread = new ImageDownloader();
		}
		
		return activeThread;
	}
	
	/**
	 * This is overriding the method in Downloader because we had images with the same name, 
	 * but different sub-directories.
	 * @param name The URL to parse.
	 * @return The name to use for the file once downloaded.
	 */
	public static String parseFilename(String name){
		if(name.contains("/")){
			String[] split = name.split("\\/");
			name = split[split.length-2]+split[split.length-1];
		}
		name = name.split("\\.")[0]+FILE_ROOT;
		return name;
	}
	
	public void addFileToDownload(String url, ImageView view, RssItemAdapter context){
		File outputDir = null;
		try{
			outputDir = new File(Utils.getAppDirectory(), IMAGE_DIR);
			if(! outputDir.exists()) outputDir.mkdirs();
		}catch(IOException ioe){}
		File outFile = new File(outputDir, parseFilename(url));
		
		if(outFile.exists()){
			InputStream inStream = null;
			try{
				Log.d(getClass().getSimpleName(), "Loading existing file");
				inStream = new FileInputStream(outFile);
				Drawable image = Drawable.createFromStream(inStream, "src");
				view.setImageDrawable(image);
				return;
			}catch(IOException ioe){
			}finally{
				try{ if(inStream != null) inStream.close(); }catch(Exception e){}
			}
		}

		Log.d(getClass().getSimpleName(), "Downloading");
		ImgDownloadFile iofn = new ImgDownloadFile();
		iofn.inputUrl = url;
		iofn.handler = new ImageHandler(view);
		iofn.context = context;
		if(outputDir != null){
			iofn.outputDirectory = outputDir;
			iofn.outputFilename = outFile.getName();
		}
		downloadQueue.offer(iofn);
	}

	@Override
	protected void downloadFile(BgDownloadFile file, Context context,
			boolean externalOnly) throws IOException 
	{
		if(!(file instanceof ImgDownloadFile)) return;
		ImgDownloadFile img = (ImgDownloadFile)file;
		
		URL imgUrl = new URL(img.inputUrl);
		URLConnection imgConn = imgUrl.openConnection();
		if(imgConn instanceof HttpURLConnection){
			InputStream inStream = ((HttpURLConnection)imgConn).getInputStream();
			if(img.outputDirectory != null && !GeneralUtils.isEmpty(img.outputFilename)){
				File imageCache = new File(img.outputDirectory, img.outputFilename);
				FileOutputStream fileOutStream = null;
				try{
					if(!imageCache.exists()){
						fileOutStream = new FileOutputStream(imageCache);
						IOUtils.copy(inStream, fileOutStream);
					}
					inStream.close();
					inStream = new FileInputStream(imageCache);
				}catch(Exception e){
					Log.w(getClass().getSimpleName(), "Error downloading image.");
					e.printStackTrace();
				}finally{
					if(fileOutStream != null) try{ fileOutStream.close(); }catch(Exception e){}
				}
			}
			try{
				Drawable image = Drawable.createFromStream(inStream, "src");
				Message message = img.handler.obtainMessage(1, image);
				img.handler.sendMessage(message);
			}finally{
				try{ if(inStream != null) inStream.close(); }catch(Exception e){}
			}
		}
	}
	
	public static class ImgDownloadFile extends Downloader.BgDownloadFile
	{
		public ImageHandler handler = null;
		public RssItemAdapter context;
	}
	
	public static class ImageHandler extends Handler
	{
		public ImageView imageView = null;
		
		public ImageHandler(ImageView view){
			imageView = view;
		}
		
        @Override
        public void handleMessage(Message message) {
        	if(imageView != null)
        		imageView.setImageDrawable((Drawable) message.obj);
        }
	}
}
